package com.tater;

import cn.hutool.core.util.RandomUtil;
import com.tater.config.NettyConfig;
import com.tater.handler.ServerHandler;
import com.tater.pojo.ResponseTime;
import com.tater.server.NettyServer;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * @author Administrator
 */
@SpringBootApplication
public class ProviderApplication implements CommandLineRunner {

    public static void main(String[] args) {
            SpringApplication.run(ProviderApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        startAndRegist();
    }

    public void startAndRegist(){
        int serverPort = RandomUtil.randomInt(10000, 30000);
        ZkClient zkClient = new ZkClient(NettyConfig.ZK_ADDRESS);
        String host="127.0.0.1";
        boolean exists = zkClient.exists(NettyConfig.SERVER_NODE);
        if (!exists){
            zkClient.createPersistent(NettyConfig.SERVER_NODE);
        }
        try {
            new NettyServer(serverHandler(), serverPort).start();
            ResponseTime time=new ResponseTime();
            time.setCallTime(LocalDateTime.now());
            time.setDoneTime(0L);
            zkClient.createEphemeral(NettyConfig.SERVER_NODE+"/"+ host+":"+serverPort,time);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Bean
    public ServerHandler serverHandler() {
        return new ServerHandler();
    }
}
